package pikes.peak;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.servlet.support.RequestContext;

import pikes.html.xhtml.Body;
import pikes.html.xhtml.XHTMLPage;

public class ConfigurablePage extends XHTMLPage {

	public static final RequestProperty<CharSequence> EMPTY_TITLE = new RequestIndependentProperty<CharSequence>("");

	private RequestProperty<CharSequence> title = EMPTY_TITLE;

	private List<BlockComponent> components = new LinkedList<BlockComponent>();

	public RequestProperty<CharSequence> getTitle() {
		return title;
	}

	public void setTitle(RequestProperty<CharSequence> title) {
		if (title == null) {
			this.title = EMPTY_TITLE;
		}
		else {
			this.title = title;
		}
	}

	public List<BlockComponent> getComponents() {
		return components;
	}

	public void setComponents(List<BlockComponent> components) {
		if (components == null) {
			this.components = Collections.EMPTY_LIST;
		}
		else {
			this.components = components;
		}

	}

	@Override
	final protected CharSequence getTitle(Map model, HttpServletRequest request) throws Exception {
		return title.getValue(model, new RequestContext(request));
	}

	@Override
	final protected void buildBody(Body body, Map model, HttpServletRequest request) throws Exception {

		RequestContext requestContext = new RequestContext(request);

		for (BlockComponent component : components) {
			body.add(component.createHtml(model, requestContext));
		}

	}

}
